package com.jiangjiang.eshop.auth.operation;

import com.jiangjiang.eshop.auth.domain.PriorityEntity;
import com.jiangjiang.eshop.auth.dto.PriorityNode;
import com.jiangjiang.eshop.auth.service.AccountPriorityRelationShipService;
import com.jiangjiang.eshop.auth.service.PriorityService;
import com.jiangjiang.eshop.auth.service.RolePriorityRelationShipService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName PriorityNodeRelateCheckVisitor
 * @Description 权限树关联检查访问者
 * @Author jhw
 * @Date 2021/5/8 10:55
 * @Version 1.0
 **/
@Slf4j
@Component
@Scope("prototype")
public class PriorityNodeRelateCheckOperation implements PriorityOperation<Boolean> {

    /**
     * 权限管理模块的门面类
     */
    @Autowired
    private PriorityService priorityService;
    /**
     * 角色和权限关系管理模块的service
     */
    @Autowired
    private RolePriorityRelationShipService rolePriorityRelationShipService;
    /**
     * 账号和权限关系管理模块的service
     */
    @Autowired
    private AccountPriorityRelationShipService accountPriorityRelationShipService;


    @Override
    public Boolean doExecute(PriorityNode node) throws Exception {
        List<PriorityEntity> priorityEntities = priorityService
                .listChildrenPriorities(node.getId());

        for (PriorityEntity entity : priorityEntities) {
            PriorityNode priorityNode = new PriorityNode();
            BeanUtils.copyProperties(entity, priorityNode);
            priorityNode.execute(this);
        }

        return relateCheck(node);
    }

    /**
     * 检查权限是否被任何一个角色或者是账号关联了
     *
     * @param node 权限树节点
     * @return 是否被任何一个角色或者是账号关联了，如果有关联则为true；如果没有关联则为false
     */
    private Boolean relateCheck(PriorityNode node) {
        Integer roleRelatedCount = rolePriorityRelationShipService
                .countByPriorityId(node.getId());
        if (roleRelatedCount != null && roleRelatedCount > 0) {
            return true;
        }

        Integer accountRelatedCount = accountPriorityRelationShipService
                .countByPriorityId(node.getId());
        if (accountRelatedCount != null && accountRelatedCount > 0) {
            return true;
        }
        return false;
    }
}
